//https://leetcode.cn/problems/combination-sum-ii/
package codeRandomThoughts.Test40组合总和II;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution2 {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> result = new ArrayList<>();
    int sum = 0;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0);
        return result;
    }

    public void backtracking(int[] candidates, int target, int startIndex) {
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        if (sum > target) return;

        boolean[] used = new boolean[51];
        for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
            if (!used[candidates[i]]) {
                used[candidates[i]] = true;
                path.add(candidates[i]);
                sum += candidates[i];
                backtracking(candidates, target, i + 1);
                sum -= candidates[i];
                path.remove(path.size() - 1);
            }
        }
    }
}
